package ru.aptu.gsp_banking.utils;

import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: alex
 * Date: 2/8/12
 * Time: 4:43 PM
 */

@Component
public class GoogleCurrencyGrabber implements CurrencyGrabber {

    // The file is located in src/main/webapp/WEB-INF/classes
    private static final String CONFIG_FILE = "/http_proxy.properties";

    protected static final String lookUp = "<span class=bld>";

    public Float parseRate(BufferedReader inputReader, String currency) throws IOException {
        String str = "";
        while ((str = inputReader.readLine()) != null) {

            int pos = str.indexOf(lookUp);
            if (pos != -1) {
                pos += lookUp.length();
                int currencyPos = str.indexOf(currency, pos);

                return Float.parseFloat(str.substring(pos, currencyPos - 1));

            }
        }
        return null;
    }

    public Float getExchangeRate(String currency, String nativeCurrency) {
        try {
            URL convert = new URL("http://www.google.com/finance/converter?a=1.0&from=" +
                    currency + "&to=" + nativeCurrency);

            InputStream inputStream = GoogleCurrencyGrabber.class.getResourceAsStream(CONFIG_FILE);

            Properties properties = new Properties();

            try {
                properties.load(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
            Boolean USE_PROXY = Boolean.parseBoolean(properties.getProperty("use_proxy"));
            Proxy PROXY = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(
                    properties.getProperty("http_proxy"), Integer.parseInt(properties.getProperty("port"))));

            URLConnection connection = USE_PROXY ?
                    convert.openConnection(PROXY) : convert.openConnection();

            return parseRate(new BufferedReader(new InputStreamReader(connection.getInputStream())), nativeCurrency);

        } catch (MalformedURLException mue) {
            System.err.println("Error requesting currency");
            return new Float(0.0);
        } catch (IOException ioe) {
            System.err.println("Error requesting currency");
            return new Float(0.0);
        }
    }
}
